"""
    @Author  ：思念 
    @File    ：9.bs4进阶使用.py
    @Date    ：2024/12/6 15:20 
"""
from bs4 import BeautifulSoup

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(html, "lxml")
# res = soup.find_all(string=["Tillie","Elsie","Lacie"])
# print(res)

"""
    css选择器编写注意事项：
        ● 标签名称不加任何修饰
        ● 类名前加.
        ● id属性名称前加
"""
# 1.标签选择器
res = soup.select("title")
print(res)
res = soup.select("a")
print(res)
res = soup.select_one("a")  # 出现的第一个a标签
print(res)

# 2.类选择器
res = soup.select(".sister")
print(res)

# 3.id选择器
res = soup.select("#link1")
print(res)

# 4.层级选择器
res = soup.select("p #link2")
print(res)

# 5.属性选择器
res = soup.select("a[href]")
print(res)
res = soup.select("p[class = 'story']")
print(res)
# 获取文本内容
print("文本内容：", soup.find('title').get_text())
print("文本内容：", soup.select('title')[0].get_text())


for i in soup.find_all('a', class_='sister'):
    print("文本内容：", i.get_text())

# 获取标签属性值
print("标签属性和值：", soup.find('a', class_='sister').attrs)

for i in soup.find_all('a'):
    print("a标签href属性值：", i.get('href'))


